package com.yifi.system.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.yifi.common.DBHelper;
import com.yifi.common.UserAgentUtil;
import com.yifi.common.utils.DateUtils;
import com.yifi.common.utils.DbUtils;
import com.yifi.common.utils.ToolWeb;

import cn.hutool.core.date.DateUtil;
import cz.mallat.uasparser.UserAgentInfo;

/**
 * 2020-04-13
 * @author yao
 *管理在线用户表
 */
public class OnLineServcie {

	public boolean setOnLine(HttpServletRequest request,String user)
	{
		String cookie = request.getHeader("Cookie");
		
		String requestPath = ToolWeb.getRequestURIWithParam(request);
		String ip = ToolWeb.getIpAddr(request);
		String referer = request.getHeader("Referer");
		String userAgent = request.getHeader("User-Agent");
		UserAgentInfo userAgentInfo = null;
		try {
			userAgentInfo = UserAgentUtil.uasParser.parse(userAgent);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String osfamily = userAgentInfo.getOsFamily();
		String osname = userAgentInfo.getOsName();
		String uafamily = userAgentInfo.getUaFamily();
		String browserversioninfo = userAgentInfo.getBrowserVersionInfo();
		String devicetype = userAgentInfo.getDeviceType();
		String uaname = userAgentInfo.getUaName();
		String type = userAgentInfo.getType();
		
		String sessionid=getSessionId(request);	//cookie.substring(cookie.indexOf("=")+1,cookie.indexOf(";"));
		
		String sql="select count(1) from sys_user_online where login_name=? and sessionid<>?";
		if(Db.queryInt(sql,user,sessionid).intValue()>0)
		{
			if(PropKit.use("jdbc.properties").getInt("config.login_session")==1)
			{
				//如果已登录过账号，那删除原来登录的sessionid；实现唯一登录
				Db.update("delete from sys_user_online where login_name=?",user);
			}
		}
		
		sql = "delete from sys_user_online where last_access_time<DATE_ADD(now(),INTERVAL -20 HOUR)";//大于20小时的自动取消登录，登录失效
		Db.update(sql);
		
		sql="select * from sys_user_online where sessionid=?  ";
		Record record=Db.findFirst(sql,sessionid);
		boolean isedit=true;
		if(record==null)
		{
			isedit=false;
			record=new Record();
			record.set("sessionid", sessionid);
			record.set("login_name", user);
			record.set("ipaddr", ip);
			record.set("browser", uaname);
			record.set("os", osname);
			record.set("login_name", user);
			record.set("start_time", DateUtils.getNowDate());
			record.set("status", "在线");
		}
		record.set("last_access_time", DateUtils.getNowDate());
		
		return DbUtils.save("sys_user_online", "sessionid", record, isedit);
	}
	
	public boolean unlineUser(String sessionid)
	{
		String sql="delete from sys_user_online where sessionid=?";
		
		return (Db.update(sql, sessionid)>0);
	}
	
	public boolean unline(HttpServletRequest request)
	{
		String sessionid=getSessionId(request);	//cookie.substring(cookie.indexOf("=")+1,cookie.indexOf(";"));

		String sql="delete from sys_user_online where sessionid=?";
		return (Db.update(sql, sessionid)>0);
	}
	
	public List<String> getSessionIds(String user)
	{
		String sql="select sessionid from sys_user_online where login_name=?";
		List<Record> list=Db.find(sql,user);
		List<String> listSession=new ArrayList<String>();
		for (Record record : list) {
			listSession.add(record.getStr("sessionid"));
		}
		
		return listSession; 
	}
	
	public String getSessionId(HttpServletRequest request)
	{
		String cookie = request.getHeader("Cookie");
		String sessionid=request.getSession().getId();
		/*if(cookie.contains(".node0")&&cookie.contains("JSESSIONID="))
		{
			sessionid=cookie.substring(cookie.indexOf("JSESSIONID=")+1,cookie.indexOf(".node0"));
		}
		else if(cookie.contains("JSESSIONID=")&&!cookie.contains(".node0"))
		{
			sessionid=cookie.substring(cookie.indexOf("JSESSIONID=")+1);
		}*/
		/*sessionid=request.getRequestedSessionId();
		sessionid=sessionid.substring(0, sessionid.lastIndexOf(".node0"));*/
		return sessionid;
	}
}
